<?php

namespace Data;

class OAuth extends Base {

	const TYPE_QQ = 1;
	const TYPE_WEIBO = 2;

	public function replaceInfo($data) {
		$condition = array(
			'Type' => $data['Type'],
			'OpenId' => $data['OpenId'],
		);
		$result = $this->where($condition)->findOne();
		if ($result) {
			$data['UpdateTime'] = time();
			$this->where($condition)->update($data);
			return $result['OAuthId'];
		} else {
			$data['UpdateTime'] = $data['CreateTime'] = time();
			return $this->insert($data);
		}
	}

	public function getById($id) {
		$condition = array(
			'OAuthId' => $id,
		);
		return $this->where($condition)->findOne();
	}

	public function getUserIdByAuthId($authId) {
		$condition = array(
			'OAuthId' => $authId,
		);
		$result = $this->select('UserId')->from('OAuthUser')->where($condition)->findOne();
		return $result ? (int) $result['UserId'] : 0;
	}

	public function addOAuthUser($userId, $authId) {
		$data = array(
			'UserId' => $userId,
			'OAuthId' => $authId,
		);
		$this->from('OAuthUser')->insert($data);
	}
}